var db = require('./dirtleWrapper');
var NOTE_TABLE_NAME = 'note';

// make sure the Note table is created
db.createTable(NOTE_TABLE_NAME);

function Note(text, date, user_id) {
    this.text = text;
    this.date = date;
    this.user_id = user_id;
}

function addNote(text, date, user_id) {
    console.log("Adding note : " + text + " -- " + date + " -- " + user_id);
    db.insertItem(NOTE_TABLE_NAME, new Note(text, date, user_id));
}
exports.addNote = addNote;

function getAllNotes(text, date, user_id) {
    if (text == null && date == null && user_id == null) {
        return db.findAllItems(NOTE_TABLE_NAME);
    } else {
        var fieldArray = [];
        var valueArray = [];
        if (text != null) {
            fieldArray.push("text");
            valueArray.push(text);
        }
        if (date != null) {
            fieldArray.push("date");
            valueArray.push(date);
        }
        if (user_id != null) { // /!\ USER ID MUST BE GIVEN !!!! /!\
            fieldArray.push("user_id");
            valueArray.push(user_id);
        }
        return db.selectItems(NOTE_TABLE_NAME, fieldArray, valueArray)
    }
}
exports.getAllNotes = getAllNotes;

function deleteNote(note_id) {
    db.removeItem(NOTE_TABLE_NAME, {id: note_id});
}
exports.deleteNote = deleteNote;

function editNote(text, date, note_id) {
    var newNote = db.findItemById(NOTE_TABLE_NAME, note_id);
    newNote.text = text;
    newNote.date = date;
    db.updateItem(NOTE_TABLE_NAME, newNote);
}
exports.editNote = editNote;

function getNoteById(note_id) {
    var notes = db.selectItems(NOTE_TABLE_NAME, ['id'], [note_id]);
    if (notes != null && notes.length == 1) {
        return notes[0];
    } else {
        return null;
    }
}